package ee.subjects.frontend.controller.command;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import ee.subjects.backend.model.data.Address;
import ee.subjects.backend.model.data.Contact;
import ee.subjects.backend.model.data.Person;
import ee.subjects.backend.model.data.subjectdbtypetablesconstants.SubjectDBTypeTablesConstants;
import ee.subjects.backend.services.PersonService;
import ee.subjects.backend.services.PersonServiceImpl;

public class EditPersonCommand implements Command {

	@SuppressWarnings("null")
	@Override
	public int execute(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		try{
			if (request.getParameter("id") != null){
				int personId=Integer.parseInt(request.getParameter("id"));
				
				PersonService PersonService = new PersonServiceImpl();
				
				Person person = PersonService.getPersonById(personId);
				request.setAttribute ("Person", person);
				
				// All addresses
				List<Address> allAddresses = PersonService.getAllPersonAddressesWithAddress_type(personId); 
				
				// Find sort main and additional addresses
				Address mainAddress=null;
				List<Address> additionalAddresses = new ArrayList<Address>();
				int personMainAddressType=SubjectDBTypeTablesConstants.ADDRESS_TYPE_PERSON_MAIN_ADDRESS;
				for (Address address : allAddresses){
					if(address.getAddress_type().getAddress_type()==personMainAddressType){
						mainAddress=address;
					}else{
						additionalAddresses.add(address);
					}
				}
				
				request.setAttribute ("MainAddress", mainAddress);
				request.setAttribute ("AdditionalAddresses", additionalAddresses);
				
			}
			
		}catch(Exception ex){
			System.out.println(ex.getStackTrace());
			System.out.println(ex.getMessage());
			
		}
		
		return 0;
	}

}
